using System.Runtime.CompilerServices;
using Microsoft.EntityFrameworkCore;
using AdminSG3L.Infrastructure;
using AdminSG3L.Infrastructure.Data;
using Serilog;
using Serilog.Events;
using AdminSG3L.Applicaticn;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using AdminSG3L.Api;


[assembly: InternalsVisibleTo("AdminSG3L.ApiTests")]

/// <summary>
/// 应用程序入口点
/// AdminSG3L 通用管理系统
/// </summary>
public class Program
{
    /// <summary>
    /// 应用程序主入口方法
    /// </summary>
    /// <param name="args">命令行参数</param>
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // 配置Serilog日志 - 从配置文件读取，写入PostgreSQL数据库和控制台
        builder.Host.UseSerilog((context, configuration) => 
        {
            configuration.ReadFrom.Configuration(context.Configuration)
                .WriteTo.Console()
                .WriteTo.PostgreSQL(
                    connectionString: context.Configuration.GetConnectionString("Postgres"),
                    tableName: "AppLogs",
                    needAutoCreateTable: true);
        });

        // ====================================
        // 数据库配置
        // ====================================
        ConfigureDatabase(builder);

        // ====================================
        // 服务注册
        // ====================================
        RegisterServices(builder);

        // ====================================
        // 认证和授权配置
        // ====================================
        ConfigureAuthentication(builder);

        var app = builder.Build();

        // ====================================
        // 中间件配置
        // ====================================
        ConfigureMiddleware(app);

        // ====================================
        // 数据库初始化
        // ====================================
        InitializeDatabase(app);
        
        app.MapControllers();
        app.Run();
    }

    /// <summary>
    /// 配置数据库连接
    /// </summary>
    /// <param name="builder">应用程序构建器</param>
    private static void ConfigureDatabase(WebApplicationBuilder builder)
    {
        var mysqlConfig = builder.Configuration.GetConnectionString("Mysql");
        var postgresConfig = builder.Configuration.GetConnectionString("Postgres");
        
        var logger = Log.ForContext<Program>();
        logger.Information("MySQL配置: {Status}", string.IsNullOrEmpty(mysqlConfig) ? "未找到" : "已加载");
        logger.Information("PostgreSQL配置: {Status}", string.IsNullOrEmpty(postgresConfig) ? "未找到" : "已加载");

        // 根据配置选择数据库（默认使用PostgreSQL）
        var dbProvider = builder.Configuration["Database:Options"] ?? builder.Configuration["Database:Default"];
        logger.Information("使用数据库: {Provider}", dbProvider);

        if (dbProvider == null)
        {
            throw new InvalidOperationException("未配置数据库连接字符串");
        }

        if (dbProvider.Equals("Mysql", StringComparison.OrdinalIgnoreCase))
        {
            builder.Services.AddInfrastructure(builder.Configuration, "MySQL");
        }
        else
        {
            builder.Services.AddInfrastructure(builder.Configuration);
        }
    }

    /// <summary>
    /// 注册应用服务
    /// </summary>
    /// <param name="builder">应用程序构建器</param>
    private static void RegisterServices(WebApplicationBuilder builder)
    {
        // 注册应用服务
        builder.Services.AddApplication(builder.Configuration);

        // 注册API相关服务
        builder.Services.AddControllers();
        builder.Services.AddHealthChecks();

        // 注册数据库初始化服务
        builder.Services.AddScoped<DatabaseInitializationService>();

        // 添加CORS策略（开发环境允许所有来源）
        builder.Services.AddCors(options =>
        {
            options.AddPolicy("AllowAll", policy =>
            {
                policy.AllowAnyOrigin()
                      .AllowAnyMethod()
                      .AllowAnyHeader();
            });
        });
    }

    /// <summary>
    /// 配置JWT认证
    /// </summary>
    /// <param name="builder">应用程序构建器</param>
    private static void ConfigureAuthentication(WebApplicationBuilder builder)
    {
        var jwtSection = builder.Configuration.GetSection("Jwt");
        var jwtSecret = jwtSection["Secret"];
        
        if (string.IsNullOrWhiteSpace(jwtSecret))
        {
            throw new InvalidOperationException("JWT密钥未配置，请在appsettings.json中设置Jwt:Secret");
        }

        builder.Services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret))
            };
        });
    }

    /// <summary>
    /// 配置中间件管道
    /// </summary>
    /// <param name="app">应用程序实例</param>
    private static void ConfigureMiddleware(WebApplication app)
    {
        // 配置健康检查端点
        app.MapHealthChecks("/health");

        // 启用CORS
        app.UseCors("AllowAll");

        // 启用认证和授权
        app.UseAuthentication();
        app.UseAuthorization();
    }

    /// <summary>
    /// 初始化数据库
    /// </summary>
    /// <param name="app">应用程序实例</param>
    private static void InitializeDatabase(WebApplication app)
    {
        var logger = Log.ForContext<Program>();
        logger.Information("开始数据库初始化");
        
        // 立即初始化数据库并添加系统数据
        using var scope = app.Services.CreateScope();
        try
        {
            // 使用新的数据库初始化服务
            var databaseInitService = scope.ServiceProvider.GetRequiredService<DatabaseInitializationService>();
            databaseInitService.InitializeDatabaseAsync().Wait();
            
            logger.Information("数据库初始化完成");
            
            var dbContext = scope.ServiceProvider.GetRequiredService<AdminDbContext>();
            var userCount = dbContext.Users.Count();
            var roleCount = dbContext.Roles.Count();
            var permissionCount = dbContext.Permissions.Count();
            var menuCount = dbContext.Menus.Count();
            
            logger.Information("当前数据库统计 - 用户: {UserCount}, 角色: {RoleCount}, 权限: {PermissionCount}, 菜单: {MenuCount}", 
                userCount, roleCount, permissionCount, menuCount);
        }
        catch (Exception ex)
        {
            logger.Error(ex, "数据库初始化失败");
        }
    }
}
